<template>
    <div>
        <!-- 页面标题 -->
        <div class="headline">员工管理</div>
        <!-- 筛选区 -->
        <div class="search-box">
            <div class="btn-left">
                <el-badge :value="typeCountMap.entry" class="custom-badge" :max="1000">
                    <el-button size="default" @click="filterByType('entry')" class="badge-btn">
                        入职
                    </el-button>
                </el-badge>
                <el-badge :value="typeCountMap.leave" class="custom-badge" :max="1000">
                    <el-button type="danger" size="default" @click="filterByType('leave')" class="badge-btn">
                        离职
                    </el-button>
                </el-badge>
                <el-badge :value="typeCountMap.long_dispatch" class="custom-badge" :max="1000">
                    <el-button size="default" @click="filterByType('long_dispatch')" class="badge-btn">
                        长期派遣
                    </el-button>
                </el-badge>
                <el-badge :value="typeCountMap.short_dispatch" class="custom-badge" :max="1000">
                    <el-button size="default" @click="filterByType('short_dispatch')" class="badge-btn">
                        短期派遣
                    </el-button>
                </el-badge>
                <el-badge :value="typeCountMap.trainee" class="custom-badge" :max="1000">
                    <el-button size="default" @click="filterByType('trainee')" class="badge-btn">
                        学员
                    </el-button>
                </el-badge>
                <el-badge :value="typeCountMap.duplicate" class="custom-badge" :max="1000">
                    <el-button size="default" @click="filterByType('duplicate')" class="badge-btn">
                        重复人员
                    </el-button>
                </el-badge>
                <el-button size="default" @click="resetFilters">重置</el-button>
            </div>
            <div class="btn-right">
                <el-button type="danger" size="default" @click="batchDelete" class="badge-btn">
                    批量删除
                </el-button>
                <el-button type="success" size="default">导出员工</el-button>
                <el-button type="primary" size="default">导入员工</el-button>
            </div>
        </div>

        <!-- 搜索区 -->
        <div class="input-box">
            <div class="input-left">
                <el-input v-model="nameKey" placeholder="请输入员工姓名" :suffix-icon="Search" @keyup.enter="applyFilters"
                    @clear="applyFilters" @input="applyFilters" class="input-item" />
                <el-select v-model="companyValue" placeholder="请选择公司" clearable @change="applyFilters"
                    class="input-item">
                    <el-option v-for="item in companyOptions" :key="item.id" :label="item.account" :value="item.id" />
                </el-select>
                <el-input v-model="projectKey" placeholder="请输入项目名称" :suffix-icon="Search" @keyup.enter="applyFilters"
                    @clear="applyFilters" @input="applyFilters" class="input-item" />
                <el-tree-select v-model="gradeValue" placeholder="请选择档级" clearable :data="gradeTreeData"
                    value-key="value" label-key="label" :props="{ children: 'children' }" @change="applyFilters" />
                <el-select v-model="certValue" placeholder="请选择证书" clearable @change="applyFilters" class="input-item">
                    <el-option v-for="item in certOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-date-picker v-model="dateValue" type="month" clearable placeholder="请选择年月" @change="applyFilters"
                    class="input-item" />
            </div>
            <div class="input-right">
                <el-button type="primary" size="default" @click="dialogVisible = true">新增</el-button>
            </div>
        </div>

        <!-- 员工列表表格-->
        <el-table :data="currentPageData" style="width: 100%" border stripe v-loading="loading"
            @selection-change="handleSelectionChange">
            <el-table-column fixed type="selection" width="50" align="center" />
            <el-table-column fixed prop="name" label="姓名" width="100" align="center">
                <template #default="scope">
                    <span class="clickable-name" @click="viewEmployee(scope.row)">{{ scope.row.name }}</span>
                </template>
            </el-table-column>
            <el-table-column fixed prop="base_pay" label="岗位工资" width="100" align="center" />
            <el-table-column fixed prop="grade_title" label="岗位档级" width="100" align="center" />
            <el-table-column fixed prop="sex" label="性别" width="80" align="center" />
            <el-table-column prop="birthday" label="生日" width="150" align="center" />
            <el-table-column prop="tel" label="手机号" width="150" align="center" />
            <el-table-column prop="idcard" label="身份证号" width="180" align="center" />
            <el-table-column prop="title" label="项目名称" width="150" align="center" />
            <el-table-column prop="account" label="公司名称" width="150" align="center" />
            <el-table-column prop="political_status" label="政治面貌" width="80" align="center" />
            <el-table-column prop="address" label="籍贯" width="150" align="center" />
            <el-table-column prop="record" label="学历" width="120" align="center" />
            <el-table-column prop="create_time" label="创建时间" width="150" align="center" />
            <el-table-column prop="status" label="员工状态" width="100" align="center">
                <template #default="scope">
                    {{ formatStatus(scope.row.status) }}
                </template>
            </el-table-column>
            <el-table-column prop="layout" label="用工形式" width="100" align="center">
                <template #default="scope">
                    {{ formatLayout(scope.row.layout) }}
                </template>
            </el-table-column>
            <el-table-column prop="entry_time" label="入职时间" width="150" align="center" />
            <el-table-column prop="agreement_end" label="合同到期时间" width="150" align="center" />
            <el-table-column prop="agreement_num" label="现合同期限" width="140" align="center" />
            <el-table-column prop="bank_card" label="银行卡号" width="200" align="center" />
            <el-table-column prop="bank" label="工资卡开户行" width="200" align="center" />
            <el-table-column prop="leave_time" label="离职时间" width="150" align="center" />
            <el-table-column fixed="right" label="操作" width="150" align="center">
                <template #default="scope">
                    <el-dropdown>
                        <span class="operate-dropdown-link">
                            更多<el-icon class="el-icon--right">
                                <ArrowDown />
                            </el-icon>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item command="adjustGrade">档级调整</el-dropdown-item>
                                <el-dropdown-item command="adjustPosition">岗位调整</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="page">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[10, 20, 50]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="filteredData.length"
                style="margin-top: 20px; text-align: right" />
        </div>

        <!-- 添加员工弹窗 -->
        <el-dialog v-model="dialogVisible" title="添加人员信息" width="760px" :before-close="handleClose">
            <div class="add-staff-form">
                <el-form ref="staffFormRef" :model="formData" :rules="formRules" size="default" class="vertical-form">
                    <el-row :gutter="16">
                        <el-col :span="8">
                            <el-form-item label="姓名" prop="name" class="vertical-form-item" required>
                                <el-input v-model="formData.name" placeholder="请输入姓名" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="手机号" prop="tel" class="vertical-form-item" required>
                                <el-input v-model="formData.tel" placeholder="请输入手机号"
                                    @input="formData.tel = formData.tel.replace(/[^\d]/g, '')" maxlength="11" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="身份证号" prop="idcard" class="vertical-form-item" required>
                                <el-input v-model="formData.idcard" placeholder="请输入身份证号" @blur="handleIdCardBlur"
                                    maxlength="18"
                                    @input="formData.idcard = formData.idcard.replace(/[^\dXx]/g, '').toUpperCase()" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="8">
                            <el-form-item label="性别" prop="sex" class="vertical-form-item">
                                <el-select v-model="formData.sex" placeholder="输入身份证号自动填充" disabled>
                                    <el-option label="男" value="男" />
                                    <el-option label="女" value="女" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="生日" prop="birthday" class="vertical-form-item">
                                <el-date-picker v-model="formData.birthday" type="date" placeholder="输入身份证号自动填充"
                                    style="width: 100%" disabled />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="籍贯" prop="address" class="vertical-form-item" required>
                                <el-input v-model="formData.address" placeholder="请输入籍贯" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="8">
                            <el-form-item label="岗位档级" prop="gradeid" class="vertical-form-item" required>
                                <el-cascader v-model="formData.gradeid" :options="gradeTreeData" placeholder="请选择档级"
                                    @change="handleGradeChange" style="width: 100%" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="岗位工资" prop="base_pay" class="vertical-form-item">
                                <el-input v-model="formData.base_pay" placeholder="选择档级后自动填充" disabled />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="学历" prop="record" class="vertical-form-item" required>
                                <el-select v-model="formData.record" placeholder="请选择学历">
                                    <el-option label="请选择" value="" />
                                    <el-option label="高中" value="高中" />
                                    <el-option label="大专" value="大专" />
                                    <el-option label="本科" value="本科" />
                                    <el-option label="研究生" value="研究生" />
                                    <el-option label="博士" value="博士" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="8">
                            <el-form-item label="开户行" prop="bank" class="vertical-form-item" required>
                                <el-input v-model="formData.bank" placeholder="请输入开户行" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="银行卡号" prop="bank_card" class="vertical-form-item" required>
                                <el-input v-model="formData.bank_card" placeholder="请输入银行卡号"
                                    @input="formData.bank_card = formData.bank_card.replace(/[^\d]/g, '')" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="政治面貌" prop="political_status" class="vertical-form-item" required>
                                <el-select v-model="formData.political_status" placeholder="请选择政治面貌">
                                    <el-option label="请选择" value="" />
                                    <el-option label="群众" value="群众" />
                                    <el-option label="团员" value="团员" />
                                    <el-option label="党员" value="党员" />
                                    <el-option label="其他" value="其他" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="8">
                            <el-form-item label="公司" prop="companyid" class="vertical-form-item" required>
                                <el-select v-model="formData.companyid" placeholder="请选择公司"
                                    @change="handleCompanyChange">
                                    <el-option label="请选择公司" value="" />
                                    <el-option v-for="company in companyOptions" :key="company.id"
                                        :label="company.account" :value="company.id" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="项目" prop="projectid" class="vertical-form-item" required>
                                <el-select v-model="formData.projectid" placeholder="请先选择公司">
                                    <el-option v-for="project in currentCompanyProjects" :key="project.id"
                                        :label="project.title" :value="project.id" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="用工形式" prop="layout" class="vertical-form-item" required>
                                <el-select v-model="formData.layout" placeholder="请选择用工形式">
                                    <el-option label="请选择" value="" />
                                    <el-option label="长期派遣" :value="1" />
                                    <el-option label="短期派遣" :value="2" />
                                    <el-option label="学员" :value="3" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="8">
                            <el-form-item label="员工状态" prop="status" class="vertical-form-item" required>
                                <el-select v-model="formData.status" placeholder="请选择员工状态" @change="handleStatusChange">
                                    <el-option label="请选择" value="" />
                                    <el-option label="在岗" :value="1" />
                                    <el-option label="离职" :value="2" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="合同到期时间" prop="agreement_end" class="vertical-form-item" required>
                                <el-date-picker v-model="formData.agreement_end" type="date" placeholder="请选择合同到期时间"
                                    style="width: 100%" @change="formatDate('agreement_end')" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="现合同期限" prop="agreement_num" class="vertical-form-item" required>
                                <el-input v-model="formData.agreement_num" placeholder="请输入合同期限"
                                    @input="formData.agreement_num = formData.agreement_num.replace(/[^\d]/g, '')" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16">
                        <el-col :span="8">
                            <el-form-item label="入职时间" prop="entry_time" class="vertical-form-item" required>
                                <el-date-picker v-model="formData.entry_time" type="date" placeholder="请选择入职时间"
                                    style="width: 100%" @change="formatDate('entry_time')" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="离职时间" prop="leave_time" class="vertical-form-item">
                                <el-date-picker v-model="formData.leave_time" type="date" placeholder="请选择离职时间"
                                    style="width: 100%" @change="formatDate('leave_time')" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleClose" class="cancel-btn">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" class="submit-btn">确认添加</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch } from 'vue'
import { Search, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { userindexApi, useraddApi, userdelApi } from '/@/api/staff/index'
import { gradeindexApi, certclassApi, organizationApi } from "/@/api/url/index"
import { validateBankCardFormat, validateBankBin, bankBinList } from '/@/utils/toolsValidate'

// 弹窗显隐控制
const dialogVisible = ref(false)

// 表单引用
const staffFormRef = ref<FormInstance>()

// 表单数据
const formData = ref({
    name: '',           // 姓名
    tel: '',            // 手机号
    idcard: '',         // 身份证号
    sex: '',            // 性别
    birthday: '',       // 生日
    address: '',        // 籍贯
    gradeid: '',        // 岗位档级ID
    base_pay: '',       // 岗位工资
    record: '',         // 学历
    bank: '',           // 开户行
    bank_card: '',      // 银行卡号
    political_status: '', // 政治面貌
    companyid: '',      // 公司ID
    projectid: '',      // 项目ID
    layout: '',         // 用工形式
    status: '',         // 员工状态
    agreement_end: '',  // 合同到期时间
    agreement_num: '',  // 现合同期限
    entry_time: '',     // 入职时间
    leave_time: ''      // 离职时间
})

// 表单验证规则
const formRules = ref({
    name: [
        {
            required: true, message: '请输入姓名', trigger: 'change'
        }
    ],
    tel: [
        {
            required: true, message: '请输入手机号', trigger: 'change'
        },
        {
            min: 11, max: 11, message: '手机号长度应在11位数', trigger: 'change'
        },

    ],
    idcard: [
        {
            required: true, message: '请输入身份证号', trigger: 'change'
        },
        {
            pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: '请输入有效身份证号格式', trigger: 'change'
        },
        { min: 18, max: 18, message: '身份证号长度应为18位', trigger: 'change' }
    ],
    address: [
        {
            required: true, message: '请输入籍贯', trigger: 'change'
        }
    ],
    gradeid: [
        {
            required: true, message: '请选择岗位档级', trigger: 'change'
        }
    ],
    record: [
        {
            required: true, message: '请选择学历', trigger: 'change'
        }
    ],
    bank: [
        {
            required: true, message: '请输入开户行', trigger: 'change'
        }
    ],
    bank_card: [
        {
            validator: (rule, value, callback) => {
                // 校验银行卡号格式
                const formatResult = validateBankCardFormat(value);
                if (!formatResult.valid) {
                    callback(new Error(formatResult.message));
                    return;
                }
                // 校验卡号前6位是否在合作银行BIN列表中
                const binResult = validateBankBin(value, bankBinList);
                if (!binResult.valid) {
                    callback(new Error(binResult.message));
                    return;
                }
                callback();
            },
            trigger: 'change'
        }
    ],
    political_status: [
        {
            required: true, message: '请选择政治面貌', trigger: 'change'
        }
    ],
    companyid: [
        {
            required: true, message: '请选择公司', trigger: 'change'
        }
    ],
    projectid: [
        {
            required: true, message: '请选择项目', trigger: 'change'
        }
    ],
    layout: [
        {
            required: true, message: '请选择用工形式', trigger: 'change'
        }
    ],
    status: [
        {
            required: true, message: '请选择员工状态', trigger: 'change'
        }
    ],
    agreement_end: [
        {
            required: true, message: '请选择合同到期时间', trigger: 'change'
        }
    ],
    agreement_num: [
        {
            required: true, message: '请输入合同期限', trigger: 'change'
        }
    ],
    entry_time: [
        {
            required: true, message: '请选择入职时间', trigger: 'change'
        }
    ],
    leave_time: [
        {
            required: true, message: '请选择离职时间', trigger: 'change'
        }
    ]
})

// 搜索筛选绑定变量
const nameKey = ref('')
const companyValue = ref('')
const projectKey = ref('')
const gradeValue = ref('')
const dateValue = ref('')
const certValue = ref('')

// 角标
const typeCountMap = ref<Record<string, number>>({
    entry: 0,
    leave: 0,
    long_dispatch: 0,
    short_dispatch: 0,
    trainee: 0,
    duplicate: 0
})
const selectedCount = ref(0) // 表格选中数量

// 数据状态
const loading = ref(false)
const rawTableData = ref<any[]>([])     // 原始数据
const filteredData = ref<any[]>([])    // 筛选后的数据
const companyOptions = ref<any[]>([]) // 公司列表
const certOptions = ref<any[]>([])  // 所有证书列表
const gradeRawData = ref<any[]>([]) // 原始档级数据
const gradeOptions = ref<any[]>([]) // 档级选项

// 当前公司对应的项目列表
const currentCompanyProjects = computed(() => {
    if (!formData.value.companyid) return []
    const company = companyOptions.value.find(company => company.id == formData.value.companyid)
    return company?.project || []
})

// 分页配置
const currentPage = ref(1)
const pageSize = ref(10)

// 转换档级数据为树形结构
const gradeTreeData = computed(() => {
    const convertToTree = (list: any[], parentId: number = 0): { label: string; value: number; children?: any[] }[] => {
        return list
            .filter(item => item.pid === parentId)
            .map(item => ({
                label: item.title,
                value: item.id,
                children: convertToTree(list, item.id)
            }))
    }
    return convertToTree(gradeRawData.value)
})

// 计算当前页显示的数据
const currentPageData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return filteredData.value.slice(start, end)
})

// 计算各类型数量
const calculateTypeCounts = () => {
    const data = rawTableData.value
    // 入职（在岗）数量
    typeCountMap.value.entry = data.filter(item => item.status === 1).length
    // 离职数量
    typeCountMap.value.leave = data.filter(item => item.status !== 1).length
    // 长期派遣数量
    typeCountMap.value.long_dispatch = data.filter(item => item.layout === 1).length
    // 短期派遣数量
    typeCountMap.value.short_dispatch = data.filter(item => item.layout === 2).length
    // 学员数量
    typeCountMap.value.trainee = data.filter(item => item.layout === 3).length
    // 重复人员数量
    const nameMap = new Map<string, number>()
    data.forEach(item => {
        if (item.name) {
            nameMap.set(item.name, (nameMap.get(item.name) || 0) + 1)
        }
    })
    let duplicateTotal = 0
    data.forEach(item => {
        if (item.name && nameMap.get(item.name) > 1) {
            duplicateTotal++
        }
    })
    typeCountMap.value.duplicate = duplicateTotal
}

// 身份证号输入处理
const handleIdCardBlur = () => {
    const idCard = formData.value.idcard
    if (idCard.length === 18) {
        // 自动提取性别
        const genderNum = parseInt(idCard.charAt(16))
        formData.value.sex = genderNum % 2 === 0 ? '女' : '男'
        // 自动提取生日
        const year = idCard.substring(6, 10)
        const month = idCard.substring(10, 12)
        const day = idCard.substring(12, 14)
        formData.value.birthday = `${year}-${month}-${day}`
    }
}

//日期处理
const formatDate = (field: string) => {
    if (!formData.value[field]) return;
    // 将Date对象转换为YYYY-MM-DD字符串
    formData.value[field] = new Date(formData.value[field]).toISOString().split('T')[0];
};
// 档级选择处理
const handleGradeChange = (selectedPath: number[]) => {
    if (!selectedPath || selectedPath.length === 0) {
        formData.value.base_pay = '';
        return;
    }
    const currentGradeId = selectedPath[selectedPath.length - 1];
    const selectedGrade = gradeRawData.value.find(grade => grade.id === currentGradeId);
    formData.value.base_pay = selectedGrade ? (selectedGrade.money || '0.00') : '';
};
// 公司选择处理
const handleCompanyChange = (companyId: string) => {
    formData.value.projectid = ''
    if (companyId) {
        const company = companyOptions.value.find(company => company.id == companyId)
    }
}

// 员工状态变化处理
const handleStatusChange = (status: number) => {
    if (status === 1) { // 在岗
        formData.value.leave_time = ''
    } else if (status === 2 && !formData.value.leave_time) { // 离职
        formData.value.leave_time = new Date().toISOString().split('T')[0]
    }
}

// 加载证书列表数据
const certclassdata = () => {
    certclassApi().signIn({})
        .then(res => {
            certOptions.value = res.data.map((item: any) => ({
                label: item.title,
                value: item.id
            }))
        })
        .catch(err => ElMessage.error('获取证书列表失败：' + (err.msg || '网络异常')))
}

// 加载公司列表数据
const organizationdata = () => {
    organizationApi().signIn({})
        .then(res => {
            companyOptions.value = res.data || []
        })
        .catch(err => ElMessage.error('获取公司列表失败：' + (err.msg || '网络异常')))
}

// 加载档级数据
const gradeindexdata = () => {
    gradeindexApi().signIn({})
        .then(res => {
            gradeRawData.value = res.list || []
            gradeOptions.value = gradeRawData.value
        })
        .catch(err => ElMessage.error('获取档级列表失败：' + (err.msg || '网络异常')))
}

// 筛选函数
const applyFilters = () => {
    let result = [...rawTableData.value]
    // 姓名筛选
    if (nameKey.value) {
        const searchName = nameKey.value.toLowerCase()
        result = result.filter(item => item.name && item.name.toLowerCase().includes(searchName))
    }
    // 公司筛选
    if (companyValue.value) {
        result = result.filter(item => item.companyid == companyValue.value)
    }
    // 项目筛选
    if (projectKey.value) {
        const searchProject = projectKey.value.toLowerCase()
        result = result.filter(item => item.title && item.title.toLowerCase().includes(searchProject))
    }
    // 档级筛选
    if (gradeValue.value) {
        result = result.filter(item => item.gradeid == gradeValue.value)
    }
    // 证书筛选
    if (certValue.value) {
        result = result.filter(item => item.certid && item.certid.includes(certValue.value))
    }
    // 日期筛选
    if (dateValue.value) {
        const selectedDate = new Date(dateValue.value)
        const year = selectedDate.getFullYear()
        const month = selectedDate.getMonth() + 1
        result = result.filter(item => {
            if (!item.create_time) return false
            const itemDate = new Date(item.create_time)
            return itemDate.getFullYear() === year && itemDate.getMonth() + 1 === month
        })
    }
    filteredData.value = result
    currentPage.value = 1 // 重置到第一页
}

// 类型筛选函数
const filterByType = (type: string) => {
    let result = [...rawTableData.value]
    switch (type) {
        case 'entry': // 入职
            result = result.filter(item => item.status === 1)
            break
        case 'leave': // 离职
            result = result.filter(item => item.status !== 1)
            break
        case 'long_dispatch': // 长期派遣
            result = result.filter(item => item.layout === 1)
            break
        case 'short_dispatch': // 短期派遣
            result = result.filter(item => item.layout === 2)
            break
        case 'trainee': // 学员
            result = result.filter(item => item.layout === 3)
            break
        case 'duplicate': // 重复人员 
            const nameCountMap = new Map()
            result.forEach(item => {
                if (item.name) nameCountMap.set(item.name, (nameCountMap.get(item.name) || 0) + 1)
            })
            result = result.filter(item => item.name && nameCountMap.get(item.name) > 1)
            break
    }
    filteredData.value = result
    currentPage.value = 1
}

// 重置筛选
const resetFilters = () => {
    nameKey.value = ''
    companyValue.value = ''
    projectKey.value = ''
    gradeValue.value = ''
    certValue.value = ''
    dateValue.value = ''
    filteredData.value = [...rawTableData.value]
    currentPage.value = 1
    selectedCount.value = 0 // 重置选中数量
}

// 分页大小切换事件
const handleSizeChange = (val: number) => {
    pageSize.value = val
    currentPage.value = 1
}

// 页码切换事件
const handleCurrentChange = (val: number) => {
    currentPage.value = val
}

// 格式化函数
const formatStatus = (status: number) => {
    return status === 1 ? '在岗' : '离职'
}

const formatLayout = (layout: number) => {
    const layoutMap: Record<number, string> = {
        1: '长期派遣',
        2: '短期派遣',
        3: '学员',
    }
    return layoutMap[layout] || '未知'
}

// 获取员工列表数据
const getRoleList = () => {
    loading.value = true
    userindexApi().signIn({})
        .then(res => {
            rawTableData.value = res.data || []
            filteredData.value = [...rawTableData.value]
            calculateTypeCounts() // 数据加载后计算角标数量
        })
        .catch(err => {
            ElMessage.error('获取员工列表失败：' + (err.msg || '网络异常'))
        })
        .finally(() => {
            loading.value = false
        })
}

// 查看员工详情
const viewEmployee = (row: any) => {
    console.log('查看员工详情', row)
}
// 存储选中员工的ID
const selectedIds = ref<number[]>([]);

// 监听表格选择事件，更新选中的ID集合
const handleSelectionChange = (val) => {
    selectedIds.value = val.map(item => item.id);
};

// 批量删除
const batchDelete = () => {
    if (selectedIds.value.length === 0) {
        ElMessage.warning('请先选择要删除的员工');
        return;
    }
    ElMessageBox.confirm('确定要删除选中的员工吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        // 调用批量删除接口
        userdelApi().signIn({ id: selectedIds.value })
            .then(() => {
                ElMessage.success('删除成功');
                getRoleList(); // 刷新员工列表
                selectedIds.value = []; // 清空选中状态
            })
            .catch(err => {
                ElMessage.error('删除失败：' + (err.msg || '网络异常'));
            });
    }).catch(() => {
        // 取消删除时无需处理
        return;
    });
};
// 关闭弹窗
const handleClose = () => {
    staffFormRef.value?.resetFields()
    dialogVisible.value = false
}

// 表单提交
const handleSubmit = () => {
    staffFormRef.value?.validate((valid) => {
        if (valid) {
            formData.value.gradeid = formData.value.gradeid[formData.value.gradeid.length - 1];
            loading.value = true
            useraddApi().signIn(formData.value)
                .then(() => {
                    ElMessage.success('员工添加成功')
                    dialogVisible.value = false
                    getRoleList() // 刷新列表
                    handleClose() // 重置表单
                })
                .catch(err => {
                    ElMessage.error('添加员工失败：' + (err.msg || '网络异常'))
                    console.log(err.msg);

                })
                .finally(() => {
                    loading.value = false
                })
        }
    })
}

// 页面加载时初始化
onMounted(() => {
    organizationdata()
    gradeindexdata()
    certclassdata()
    getRoleList()
})
</script>

<style scoped>
.headline {
    font-size: 18px;
    margin-bottom: 20px;
}

.clickable-name {
    cursor: pointer;
    color: #2151C5;
}

/* 表格单元格样式 */
:deep(.el-table--large .el-table__cell) {
    padding: 4px 1px;
    font-size: 12px;
}

:deep(.el-table--large .cell) {
    padding: 0 10px;
}

/* 操作列下拉样式 */
.operate-dropdown-link {
    cursor: pointer;
    color: #409EFF;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

:deep(.el-dropdown) {
    display: flex;
    align-items: center;
    justify-content: center;
}

/* 搜索按钮区样式 */
.search-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.btn-left {
    display: flex;
    width: 58%;
    justify-content: space-between;
}

.btn-right {
    display: flex;
    width: 40%;
    justify-content: space-between;
}

/* 输入筛选区样式 */
.input-box {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    justify-content: space-between;
}

.input-left {
    width: 88%;
    display: flex;
    gap: 8px;
}

.input-item {
    min-width: 140px;
}

:deep(.el-input__wrapper) {
    width: 350px;
}

/* 分页样式 */
.page {
    display: flex;
    justify-content: space-evenly;
    margin-top: 16px;
    padding-right: 20px;
}

/* 添加员工表单样式 */
.vertical-form-item {
    display: flex;
    flex-direction: column;
    margin-bottom: 0;
    width: 100%;
}

/* 标签在上方样式 */
:deep(.vertical-form-item .el-form-item__label) {
    display: block;
    text-align: left;
    margin-bottom: 6px;
    padding: 0;
    height: auto;
    line-height: 1.5;
    font-weight: 500;
    width: 100%;
}

/* 表单行样式 */
:deep(.el-row) {
    margin-bottom: 15px;
    width: 100%;
    box-sizing: border-box;
}

/* 弹窗按钮样式 */
.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

.cancel-btn {
    margin-right: 16px;
}
</style>